package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/8/5 11:31
 * @Description:
 */
@RestController
@RequestMapping("/report")
public class ReportController {

	@Reference
	MemberService memberService;

	@Reference
	OrderService orderService;


	@Reference
	ReportService reportService;

    /**
     *  @描述：获取会员信息
     */
	@RequestMapping("/getMemberReport")
	public Result getMemberReport() {
		try {
			// 0.准备数据
			Map map = new HashMap<String, List>();
			List<String> months = new ArrayList<>();
			List<Integer> memberCount = new ArrayList<>();
			// 1.生成数据（months：计算，memberCount:查数据库）
			// 1-1：计算months
			LocalDate localDate = LocalDate.now().minusMonths(12);  // 2018-08
			for (int i = 0; i < 12; i++) {
				LocalDate tempDate = localDate.plusMonths(i);
				months.add(tempDate.toString().substring(0, 7));
			//System.out.println(tempDate.toString());
			}
			//  1-2:获取memberCount
			memberCount = memberService.findCountByMonth(months);



			map.put("months", months);
			map.put("memberCount", memberCount);
			return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
		} catch(Exception e){
			e.printStackTrace();
			return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
		}

	}
	
	/**
	 *  @描述：获取套餐占比统计
	 */
	@RequestMapping("/getSetmealReport")
	public Result getSetmealReport() {
		// 0.准备数据
		Map<String, List> map = new HashMap<>();
		List<String> setmealNames = new ArrayList<>();
		List<Map> setmealCount;
		// 1.生成数据
		// 1-1. 从数据库获取setmealCount
		setmealCount = orderService.findSetmealCount();
		// 1-2. 遍历setmealCount，拿到setmealNames
		setmealCount.forEach(setmeal->setmealNames.add(setmeal.get("name").toString()));
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);
		return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
	}

	/**
	 *  @描述：获取运营统计数据
	 */
	@RequestMapping("/getBusinessReportData")
	public Result getBusinessReportData() {
		Map<String, Object> map = reportService.getBusinessReportData();
		return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
	}

	public static void main(String[] args) {
		//request.getSession().getServletContext().getRealPath("template")
		LocalDate localDate = LocalDate.now().minusMonths(12);
		for (int i = 0; i < 12; i++) {
			LocalDate tempDate = localDate.plusMonths(i);
			System.out.println(tempDate.toString().substring(0,7));

		}
	}
	/**
	 *  @描述：下载运营数据报表
	 */
	@RequestMapping("/exportBusinessReport")
	public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
		// 获取运营数据
		Map<String, Object> map = reportService.getBusinessReportData();
		// 获取单项数据
		//取出返回结果数据，准备将报表数据写入到Excel文件中
		String reportDate = (String) map.get("reportDate");
		Integer todayNewMember = (Integer) map.get("todayNewMember");
		Integer totalMember = (Integer) map.get("totalMember");
		Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
		Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
		Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
		Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
		Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
		Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
		Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
		Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
		List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");


		// 获取模板路径
		String path = request
				.getSession()
				.getServletContext()
				.getRealPath("template")+ File.separator+"report_template.xlsx";
		XSSFWorkbook xssfWorkbook;

		try {
			xssfWorkbook = new XSSFWorkbook(path);

			XSSFSheet page = xssfWorkbook.getSheetAt(0);

			//	 填充单项数据
			XSSFRow row = page.getRow(2);
			row.getCell(5).setCellValue(reportDate);  //报告日期
			row = page.getRow(4);
			row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
			row.getCell(7).setCellValue(totalMember);//总会员数

			row = page.getRow(5);
			row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
			row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

			row = page.getRow(7);
			row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
			row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

			row = page.getRow(8);
			row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
			row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

			row = page.getRow(9);
			row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
			row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

			int num = 12;
			for (Map itemMap : hotSetmeal) {
				XSSFRow row1 = page.getRow(num++);
				row1.getCell(4).setCellValue(String.valueOf(itemMap.get("name")));
				row1.getCell(5).setCellValue(Integer.parseInt(itemMap.get("setmeal_count").toString()));
				row1.getCell(6).setCellValue(((BigDecimal)(itemMap.get("proportion"))).doubleValue());
			}

			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
			xssfWorkbook.write(outputStream);
			outputStream.flush();
			outputStream.close();
			xssfWorkbook.close();



		} catch (IOException e) {
			e.printStackTrace();
		}


		return null;
	}
}
